package cn.tedu.baking.service.impl;

import cn.tedu.baking.mapper.ContentMapper;
import cn.tedu.baking.pojo.dto.ContentDTO;
import cn.tedu.baking.pojo.dto.ContentManagementQueryDTO;
import cn.tedu.baking.pojo.entity.Content;
import cn.tedu.baking.pojo.vo.*;
import cn.tedu.baking.service.IContentService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.File;
import java.util.Date;
import java.util.List;

@Service
public class ContentService implements IContentService {
    @Autowired
    ContentMapper mapper;
    @Override
    public void addNew(ContentDTO contentDTO) {
        Content content = new Content();
        BeanUtils.copyProperties(contentDTO,content);

        if (contentDTO.getId()==null){//新增
            content.setCreateTime(new Date());
            mapper.insert(content);
        }else{//修改
            content.setUpdateTime(new Date());
            //设置修改人的id
            content.setUpdateBy(content.getUserId());
            mapper.update(content);
        }


    }

    @Override
    public List<ContentManagementVO> manangementList(ContentManagementQueryDTO queryDTO) {
        return mapper.selectForManagement(queryDTO);
    }
    @Value("${file-path}")
    private String dirPath;
    @Override
    public void deleteById(Long id) {
        //通过id查询到图片路径
        String imgUrl = mapper.selectImgUrlById(id);
        System.out.println(imgUrl);
        //把路径对应的文件删除
        new File(dirPath+imgUrl).delete();

        mapper.deleteById(id);
    }

    @Override
    public ContentUpdateVO updateById(Long id) {
        return mapper.selectForUpdateById(id);
    }

    @Override
    public List<ContentIndexVO> listForIndex(Integer type, Long categoryId) {
        return mapper.selectForIndexByType(type,categoryId);
    }

    @Override
    public ContentDetailVO detailById(Long id) {
        //浏览量+1
        mapper.updateViewCountById(id);
        return mapper.selectForDetailById(id);
    }

    @Override
    public List<ContentSimpleVO> otherListById(Long id) {
        return mapper.selectOtherById(id);
    }

    @Override
    public List<ContentSimpleVO> hotList() {
        return mapper.selectForHot();
    }

    @Override
    public List<ContentIndexVO> listByType(Integer type) {
        return mapper.selectByType(type);
    }

    @Override
    public List<ContentIndexVO> searchByWd(String wd) {
        return mapper.selectByWd(wd);
    }

    @Override
    public List<ContentAdminVO> listForAdmin() {
        return mapper.selectForAdmin();
    }
}
